/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.support.scripting.impl.js;

import cn.easyplatform.contexts.RecordContext;
import cn.easyplatform.dos.FieldDo;
import cn.easyplatform.dos.Record;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.support.scripting.MappingEngine;
import cn.easyplatform.support.scripting.RhinoScriptable;
import cn.easyplatform.support.scripting.ScriptParser;
import cn.easyplatform.support.scripting.ScriptUtils;
import cn.easyplatform.support.scripting.parser.MappingScriptParser;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.RhinoException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class RhinoMappingEngine implements MappingEngine {

    private final static Logger log = LoggerFactory.getLogger(RhinoMappingEngine.class);

    private RhinoScriptable scope = null;

    @Override
    public List<String> eval(CommandContext cc, RecordContext target,
                             FieldDo[] source, String script) {
        ScriptParser sp = new MappingScriptParser();
        script = sp.parse(cc, target, script.trim());
        Context cx = Context.enter();
        try {
            cx.setOptimizationLevel(-1);
            scope = new RhinoScriptable();
            scope.initStandardObjects(cx, false);
            Record record = new Record();
            for (FieldDo fd : source)
                record.set(fd);
            RecordContext rc = target.clone();
            rc.setData(record);
            // ScriptCmdExecutor cmd =
            ScriptUtils.createVariables(scope, cc, cc.getWorkflowContext(), rc,
                    target);
            cx.evaluateString(scope, RhinoScriptEngine.functions, "", 1, null);
            if (cc.getUser().isDebugEnabled())
                cc.send("script:" + script);
            else if (log.isDebugEnabled())
                log.debug("script {}", script);
            // if (cc.getUser().isDebugLogicEnabled()) {
            // cc.send(I18N.getLable("script.engine.system.var", cmd
            // .getTarget().getSystemVars()));
            // cc.send(I18N.getLable("script.engine.user.var", "onMapping"));
            // cc.send(cmd.getTarget().getUserVars());
            // cc.send(I18N.getLable("script.engine.field.var", "onMapping"));
            // cc.send(cmd.getTarget().getRecordFieldValues());
            // cc.send("script:" + script);
            // }
            cx.evaluateString(scope, script, "", 1, null);
            // if (cc.getUser().isDebugLogicEnabled()) {
            // cc.send(I18N.getLable("script.engine.system.var", cmd
            // .getTarget().getSystemVars()));
            // cc.send(I18N.getLable("script.engine.user.var", "onMapping"));
            // cc.send(cmd.getTarget().getUserVars());
            // cc.send(I18N.getLable("script.engine.field.var", "onMapping"));
            // cc.send(cmd.getTarget().getRecordFieldValues());
            // }
            return sp.getMappingFields();
        } catch (RhinoException ex) {
            throw ScriptUtils.handleScriptException(cc, ex);
        } finally {
            Context.exit();
            scope.clear();
            scope = null;
        }
    }
}
